#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : c_picture.py
@File Name  : picture.py
@Author     : LeeCQ
@Date-Time  : 2019/11/30 19:25

"""
import os

import requests
from HTTP.Download_9C_1.root_class import Root9C
from HTTP.Download_9C_1.c_mysql import MySQL9C


class Picture9C(Root9C):
    """
    这是9c的图片相关Picture类；
    目的是获取Picture集的地址；
        构建集的地址： 知道出现404错误，退出循环；

    get_all_json(): 的数据结构
    [{txt_tag: [
    ]},]
    Picture txt 文件的 数据结构：
        [one_dict{  'a_id',     int()
                    'a_name',   Name
                    'a_pic',    URL - a picture
                    'a_remarks',URL - a picture
                    'a_type',   int() 分类对应的编号
                    'a_time'    时间 -
                    }
            ], and more dict {},
    """
    DIR_ROOT = Root9C.DIR_ROOT + 'pic/'

    def __init__(self):
        self.picture_tags = [_t for _t in self.txt2tag() if _t[0] == 'pic_list']
        self.picture_api = self.api_picture()
        self._sql = MySQL9C()
        self._html_template = self.set_html_template()

    def get_json(self, choose):
        """ 这个方案更节省内存
        决定json那些数据: tags:(分类，标签，文件)
        :return [{tag: data}, ]
        """
        return [{_t[1]:self.json_one_txt(self.DIR_SUP + _t[2])} for _t in self.picture_tags
                if _t[1] == choose
                ]

    def get_all_json(self):
        """ 这个方案更灵活
        返回全部的picture的json数据 tags:(分类，标签，文件)
        :return [{tag: data}, ]
        """
        return [{_t[1]:self.json_one_txt(self.DIR_SUP + _t[2])} for _t in self.picture_tags]

    def get_json_inOne(self):
        """把所有的数据返回到一个列表里！# kind(大分类), 标签名, txt文件名, 标签代码(a_type)"""
        _temp = []
        [_temp.extend(self.json_one_txt(self.DIR_SUP + _t[2])) for _t in self.picture_tags]
        return _temp

    def api_picture(self):
        return 'http:/' + self.api_()['imgapi'].replace('//', '/')

    def get_one_javaScript(self, _id):
        """"""
        # print(self.picture_api, _id)
        while True:
            _res = requests.get(self.picture_api + _id, headers=self.create_HEADERS(self.picture_api))  # + a_id
            if _res.status_code == 200:
                return _res.text
            else: print(_id, _res.status_code)

    def get_one_pic(self, url):
        if url[:4].upper() != 'HTTP': url = 'http://' + url
        _res = requests.get(url, headers=self.create_HEADERS(url), verify=False)
        if _res.status_code == 200:
            return _res.content

    def get_all_javaScript(self):
        """"""
        for a_dict in self.get_json_inOne():
            a_dict['a_pic'] = self.get_one_pic(a_dict['a_pic'])
            a_dict['a_remarks'] = self.get_one_javaScript(a_dict['a_id'])
            # self._sql.pic_append(**a_dict)
        return 0

    @staticmethod
    def set_html_template():
        """"""
        return open('./template_pic.html', 'r', encoding='utf8').read()

    def write_html(self, a_dict):
        """
        把获取到的JavaScript替换到模板中；
        :param a_dict:
        :return:
        """
        if not os.path.exists(self.DIR_ROOT): os.mkdir(self.DIR_ROOT)
        _template = self._html_template
        _template = _template.replace('{%title%}', a_dict['a_name'])
        _template = _template.replace('{%script%}', self.get_one_javaScript(a_dict['a_id']))
        open(self.DIR_ROOT + a_dict['a_id'] + '.html', 'w', encoding='utf8').write(_template)
        return 0

    def write_html_s(self):
        """"""
        for a_dict in self.get_json_inOne():
            self.write_html(a_dict)
            # self._sql.pic_append(**a_dict)
        return 0

    def save_pictures(self):
        pass


if __name__ == '__main__':
    t = Picture9C()
    js = t.write_html_s()
    print(js)
    print(t.get_all_json())


